//
//  RAPComposeViewController.swift
//  COPYCAT-Weibo
//
//  Created by 闫萌 on 1/4/16.
//  Copyright © 2016 RendezvousAuParadis. All rights reserved.
//

import UIKit
import SVProgressHUD

private let kMargin: CGFloat = 5



class RAPComposeViewController: UIViewController, UITextViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    // MARK: - 系统方法
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        textView.becomeFirstResponder()
        
        // 监听通知
        // 键盘位移通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardMoved:", name:
            UIKeyboardWillChangeFrameNotification, object: nil)
        // 表情按钮点击通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonButtonClicked:", name:
            RAPEmoticonPresentationCellEmoticonButtonClickedNotification, object: nil)
        // 删除按钮点击通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deleteButtonClicked:", name:
            RAPEmoticonPresentationCellDeleteButtonClickedNotification, object: nil)
    }
    
    private func setupUI() {
        // 导航栏左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: "closeButtonClicked")
        
        // 设置导航栏的两个按钮
        let rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        rightBarButtonItem.enabled = false
        navigationItem.rightBarButtonItem = rightBarButtonItem
        
        // 设置导航栏中间文字
        navigationItem.titleView = userNameLabel
        
        // 添加text view
        view.addSubview(textView)
        view.addSubview(menuBar)
        textView.addSubview(gridPicturesView)
        
        
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
        
        // 添加菜单栏
        menuBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.view)
            make.leading.trailing.equalTo(self.view)
        }
        
        gridPicturesView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            // TODO: 注意，此处职能将宽度约束参照self.view添加，
            // 可能是框架的bug
            make.leading.equalTo(self.view).offset(kMargin)
            make.trailing.equalTo(self.view).offset(-kMargin)
            // 注意，此处要将宽到约束想等
            make.height.equalTo(gridPicturesView.snp_width)
        }

    }
    
    // MARK: - 自定义属性
    /*
    menuBar的动作效果如下：
    第一次进入界面，键盘自动弹出，没有动画--->
    键盘已经弹出，切换键盘，没有动画--->
    从底部切换键盘，有动画--->
    textView成为/退出第一响应者，有动画
    */
    private var shouldAnimateMenuBar: Bool = false // 进入界面时不需要
    
    // MARK: - 懒加载控件
    /*
    懒加载键盘，其只需初始化一次
    */
    private lazy var emoticonKeyboard: RAPEmoticonKeyboard = {
        let emoticonKeyboard = RAPEmoticonKeyboard()
        emoticonKeyboard.frame.size.height = RAPEmoticonKeyboardPredefinedHeight
        return emoticonKeyboard
    }()
    
    private lazy var gridPicturesView: RAPGridPicturesView = {
        let gridPicturesView = RAPGridPicturesView()
        /*
        注意，在这个闭包里使用self将造成引用循环
        */
        gridPicturesView.addButtonClickedClosure = { [unowned self] in
            
            self.selectPicture()
        }
        
        gridPicturesView.imageCountChangedClosure = { [unowned self] (count) -> () in
            // 判断是否应该disable 相机按钮
            if count == 9 {
                (self.menuBar.viewWithTag(RAPMenuBarButtonType.Camera.rawValue) as! UIButton).enabled = false
            } else {
                (self.menuBar.viewWithTag(RAPMenuBarButtonType.Camera.rawValue) as! UIButton).enabled = true
            }
            
        }
        
        return gridPicturesView
    }()
    
    private lazy var menuBar: RAPMenuBar = {
        let menuBar = RAPMenuBar(frame: CGRectZero)
        /*
        为menu bar设置回调
        */
        menuBar.buttonClickHandler = {[unowned self] (buttonType: RAPMenuBarButtonType) -> () in
            switch buttonType {
            case .Add:
                RAPLog("add")
            case .Camera:
                RAPLog("camera")
                self.selectPicture()
            case .Emoticon:
                RAPLog("emoticon")
                // 切换键盘
                self.switchKeyboard(buttonType)
            case .Keyboard:
                RAPLog("keyboard")
            case .Mention:
                RAPLog("mention")
            }
        }
        return menuBar
    }()
    
    // TODO:  随着文字的输入，配图控件不断下移还没有做
    private lazy var textView: RAPTextView = {
        let textView = RAPTextView()
        
        // 文字改变回调
        textView.textViewChangedClosure = {
            [unowned self]
            (textView: UITextView) -> () in
            if textView.hasText() {
                self.navigationItem.rightBarButtonItem?.enabled = true
            } else {
                self.navigationItem.rightBarButtonItem?.enabled = false
            }
        }
        
        // 即将退出第一响应者的回调
        textView.beginDragginClosure = {
            [unowned self]
            (textView: UITextView) -> () in
            self.shouldAnimateMenuBar = true
        }
        
        textView.font = UIFont.systemFontOfSize(20)
        textView.placeholderText = "QWERTYUIOP"
        return textView
    }()
    
    private lazy var userNameLabel: UILabel = {
        // 拼接要显示的内容
        let useName = RAPAccountViewModel.sharedViewModel.readAccountInfo()?.screen_name ?? ""
        // 创建属性字符串
        let contentString = "发微博\n\(useName)" as NSString
        let attrText = NSMutableAttributedString(string: contentString as String)
        // 设置用户名的字符串显示效果
        attrText.setAttributesForSubstring(useName, fontSize: 12, textColor: UIColor.grayColor())
        attrText.setAttributesForSubstring("发微博", fontSize: 13)

        // 创建label
        let userNameLabel = UILabel()
        userNameLabel.attributedText = attrText
        userNameLabel.numberOfLines = 0
        userNameLabel.textAlignment = .Center
        userNameLabel.sizeToFit() // 注意，必须使用，否则没有size
        
        return userNameLabel
    }()
    
    private lazy var sendButton: UIButton = {
        
        let sendButton = UIButton(title: "发送", fontSize: 14, imageName: nil, backgroundImageName: "common_button_orange", target: self, action: "sendButonClicked", textColor: UIColor.whiteColor())
        /*
         注意，当视图被添加至UITabBarItem，其sizeToFit只能确定自身内容的size，
        而非连带视图外部的size
        */
        sendButton.frame = CGRectMake(0, 0, 40, 30)
        sendButton.setBackgroundImage(UIImage(named: "common_button_white_disable")?.slicedImage(), forState: UIControlState.Disabled)
        sendButton.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Disabled)
        
        return sendButton
        
    }()
    
    // MARK: -  动作方法
    @objc private func emoticonButtonClicked(noti: NSNotification) {
        RAPLog("点击表情按钮")
        /*
        将表情图片添加至text view
        */
        // 获取表情模型
        let emoticonModel = noti.userInfo![RAPEmoticonModelKey as NSString] as! RAPEmoticonModel
        
        textView.displayEmoticonByModel(emoticonModel)

    }
    
    @objc private func deleteButtonClicked(noti: NSNotification) {
        RAPLog("点击删除按钮")
        // 从text view上删除文字
        textView.deleteBackward()
    }
    
    
    ///  切换键盘 普通键盘 / 表情键盘
    private func switchKeyboard(buttonType: RAPMenuBarButtonType) {
        // 切换键盘不需要动画效果

        /*
        按钮图标切换逻辑
        */
        let emoticonBtn = menuBar.viewWithTag(buttonType.rawValue) as! UIButton
        let currentY = CGRectGetMaxY(emoticonBtn.superview!.frame)
        
        shouldAnimateMenuBar = currentY == CGRectGetMaxY(kScreenBounds) ? true : false
        
        // 替换按钮的image
        if self.textView.inputView == nil {
            emoticonBtn.switchImage("compose_keyboardbutton_background")
        } else {
            emoticonBtn.switchImage("compose_emoticonbutton_background")
        }
        
        RAPLog("切换键盘")
        /*
        退出第一响应者--->
        切换键盘--->
        在此称为第一响应者。
        从而使键盘能够成功切换
        */
        textView.resignFirstResponder()
        textView.inputView = textView.inputView == nil ?  emoticonKeyboard : nil
        textView.becomeFirstResponder()
    }
    
    ///  弹出图片选择j界面
    private func selectPicture() {
        let imagePicker = UIImagePickerController()
        imagePicker.sourceType = .SavedPhotosAlbum
        imagePicker.delegate = self
        self.presentViewController(imagePicker, animated: true) { () -> Void in
            // 留空
        }
    }
    
    
    ///  接收到键盘frame发生改变的通知时调用
    ///
    ///  - parameter noti: 通知对象
    @objc private func keyboardMoved(noti: NSNotification) {
//        {
//            UIKeyboardAnimationCurveUserInfoKey = 7;
//            UIKeyboardAnimationDurationUserInfoKey = "0.25";
//            UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
//            UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
//            UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
        
//            UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
//            UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
        
//            UIKeyboardIsLocalUserInfoKey = 1;
//        }
        
//        let beginY = (noti.userInfo![UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().origin.y
//        let endY = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue().origin.y
//
//        if beginY < endY && shouldAnimateMenuBar == true {
//            return
//        }
        
        if let opEndY = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue().origin.y {
            menuBar.snp_updateConstraints { (make) -> Void in
                // 计算menuBar的移动位置
                make.bottom.equalTo(self.view).offset(opEndY - kScreenBounds.size.height)
            }
        }
        
        if shouldAnimateMenuBar == true {
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.menuBar.layoutIfNeeded()
                }) { (_) -> Void in
                    // 留空
            }
        }
    }
    
    @objc private func closeButtonClicked() {
        self.view.endEditing(true)
        dismissViewControllerAnimated(true) { () -> Void in
            //
        }
    }
    
    @objc private func sendButonClicked() {
        RAPLog("点击发送按钮")
        // 从text view 中获取表情字符串的组合
        let statusString = textView.emoticonCode()
        
        SVProgressHUD.show()
        navigationItem.rightBarButtonItem?.enabled = false
        RAPAFNHTTPRequestTool.sharedTool.sendStatus(statusString, image: gridPicturesView.selectedImages.first) { (responseObject, error) -> () in
            // 进行控制器跳转
            self.dismissViewControllerAnimated(true, completion: { () -> Void in
                // 留空
                self.navigationItem.rightBarButtonItem?.enabled = true
            })
            SVProgressHUD.dismiss()
            if error != nil {
                RAPLog(error)
                self.navigationItem.rightBarButtonItem?.enabled = true
            }
        }
    }
}

// MARK: - UIImagePickerControllerDelegate
extension RAPComposeViewController {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        var selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        RAPLog(selectedImage.size)
        // 对图片进行缩放，以节约内存
        selectedImage = selectedImage.scaledImage(CGSizeMake(RAPImageCellSideLength, RAPImageCellSideLength))
                RAPLog(selectedImage.size)
        // 向grid view添加图片
        gridPicturesView.addImage(selectedImage)
        dismissViewControllerAnimated(true) { () -> Void in
            // 留空
        }
        
        
        
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        //
        dismissViewControllerAnimated(true, completion: nil)
    }
}
